export class ResourceManager {
  constructor() {
    // 音效资源
    this.sounds = {
      click: wx.createInnerAudioContext(),
      dice: wx.createInnerAudioContext(),
      success: wx.createInnerAudioContext(),
      fail: wx.createInnerAudioContext()
    }
    
    // 背景音乐
    this.bgm = wx.createInnerAudioContext()
    
    // 音效开关
    this.soundEnabled = true
    
    // 图片资源
    this.images = new Map()
    
    // 初始化音效
    this.initSounds()
    
    // 初始化背景音乐
    this.initBGM()

    this.audio = new Map()
  }
  
  initSounds() {
    // 设置音效源
    this.sounds.click.src = 'audio/click.mp3'
    this.sounds.dice.src = 'audio/dice.mp3'
    this.sounds.success.src = 'audio/success.mp3'
    this.sounds.fail.src = 'audio/fail.mp3'
    
    // 设置音效属性
    Object.values(this.sounds).forEach(sound => {
      sound.volume = 0.5
    })
  }
  
  initBGM() {
    // 设置背景音乐
    this.bgm.src = 'audio/bgm.mp3'
    this.bgm.loop = true
    this.bgm.volume = 0.3
  }
  
  // 播放音效
  playSound(name) {
    if (this.sounds[name] && this.soundEnabled) {
      this.sounds[name].stop()
      this.sounds[name].play()
    }
  }
  
  // 播放背景音乐
  playBGM() {
    this.bgm.play()
  }
  
  // 停止背景音乐
  stopBGM() {
    this.bgm.stop()
  }
  
  // 暂停背景音乐
  pauseBGM() {
    this.bgm.pause()
  }
  
  // 恢复背景音乐
  resumeBGM() {
    this.bgm.play()
  }
  
  // 设置音效音量
  setSoundVolume(volume) {
    Object.values(this.sounds).forEach(sound => {
      sound.volume = volume
    })
  }
  
  // 设置背景音乐音量
  setBGMVolume(volume) {
    this.bgm.volume = volume
  }
  
  // 启用音效
  enableSound() {
    this.soundEnabled = true
  }
  
  // 禁用音效
  disableSound() {
    this.soundEnabled = false
  }
  
  // 震动反馈
  vibrate() {
    wx.vibrateShort({
      type: 'medium'
    })
  }
  
  // 清理资源
  destroy() {
    // 停止并销毁音效
    Object.values(this.sounds).forEach(sound => {
      sound.stop()
      sound.destroy()
    })
    
    // 停止并销毁背景音乐
    this.bgm.stop()
    this.bgm.destroy()
    
    // 清理图片资源
    this.images.clear()

    this.audio.clear()
  }

  // 加载图片
  loadImage(src, timeout = 10000) {
    return new Promise((resolve, reject) => {
      if (this.images.has(src)) {
        resolve(this.images.get(src))
        return
      }

      const image = wx.createImage()
      let timeoutId

      const cleanup = () => {
        if (timeoutId) {
          clearTimeout(timeoutId)
        }
      }

      image.onload = () => {
        cleanup()
        this.images.set(src, image)
        resolve(image)
      }

      image.onerror = (error) => {
        cleanup()
        reject(new Error(`Failed to load image: ${src}, error: ${error}`))
      }

      timeoutId = setTimeout(() => {
        cleanup()
        reject(new Error(`Image loading timeout: ${src}`))
      }, timeout)

      image.src = src
    })
  }

  // 获取图片
  getImage(src) {
    return this.images.get(src)
  }
} 